﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProTrack.IServices.Device;
using System;
using System.Threading.Tasks;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using System.Linq;
using ProTrack.Entity;
using System.Collections.Generic;
using ProTrack.Utility;
using ProTrack.Report;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 设备类型接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class MachineryTypeController : ControllerBase
    {
        public MachineryTypeController(IMachineryTypeServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }

        public IMachineryTypeServices Services { get; }
        public LogHelper LogHelper { get; }


        /// <summary>
        /// 获取设备类型
        /// </summary>
        /// <param name="MachineryTypeCode">设备类型编码</param>
        /// <param name="MachineryTypeName">设备类型名称</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] string MachineryTypeCode, [FromQuery] string MachineryTypeName)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                MachineryTypeCode = MachineryTypeCode ?? "";
                MachineryTypeCode = MachineryTypeCode ?? "";
                var list = await Services.GetAsync(MachineryTypeCode, MachineryTypeName);


                //递归处理 树形菜单数据
                var dataList = TreeData(list);
                status.Count = dataList.Count;
                status.Data = dataList;

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-获取树形数据", ex, HttpContext);
            }
            return Ok(status);
        }



        /// <summary>
        /// 获取所有已启用的设备类型
        /// </summary>
        /// <param name="MachineryTypeCode">设备编码</param>
        /// <param name="MachineryTypeName">设备名称</param>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll([FromQuery] string MachineryTypeCode, [FromQuery] string MachineryTypeName)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                MachineryTypeCode = MachineryTypeCode ?? "";
                MachineryTypeCode = MachineryTypeCode ?? "";
                var list = await Services.GetAllAsync(MachineryTypeCode, MachineryTypeName);


                //递归处理 树形菜单数据
                var dataList = TreeData(list);
                status.Count = dataList.Count;
                status.Data = dataList;

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-获取树形数据", ex, HttpContext);
            }
            return Ok(status);
        }

        #region 数据处理

        private List<MachineryTypeDto> TreeData(IEnumerable<MachineryType> list)
        {

            List<MachineryTypeDto> dataList = new List<MachineryTypeDto>();

            // 找到所有 父级
            var parent = list.Where(x => x.ParentTypeId == 0);
            //查找所有子级
            var child = list.Where(x => x.ParentTypeId != 0);


            foreach (var item in parent)
            {
                var model = new MachineryTypeDto
                {
                    Id = item.Id,
                    MachineryTypeCode = item.MachineryTypeCode,
                    MachineryTypeName = item.MachineryTypeName,
                    Remark = item.Remark,
                    EnableFlag=item.EnableFlag,
                    CreateTime = item.CreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                };
                dataList.Add(model);


                //判断当前父级是否存在子级
                var childList = list.Where(x => x.ParentTypeId == item.Id).ToList();
                if (childList.Any())
                {
                    //存在子级
                    GetChild(childList, model, list.ToList());
                }
            }


            return dataList;

        }


        void GetChild(List<MachineryType> child, MachineryTypeDto parent,List<MachineryType> AllData)
        {

            //遍历所有子级
            foreach (var item in child)
            {
                var model = new MachineryTypeDto
                {
                    Id = item.Id,
                    MachineryTypeCode = item.MachineryTypeCode,
                    MachineryTypeName = item.MachineryTypeName,
                    Remark = item.Remark,
                    ParentTypeName = parent.MachineryTypeName,
                    ParentTypeId = parent.Id,
                    EnableFlag = item.EnableFlag,
                    CreateTime = item.CreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                };
                parent.Children.Add(model);

                //判断当前父级是否存在子级
                var childList = AllData.Where(x => x.ParentTypeId == item.Id).ToList();
                if (childList.Any())
                {
                    //存在子级
                    GetChild(childList, model, AllData);
                }

            }
        }
        #endregion


        /// <summary>
        /// 新增设备
        /// </summary>
        /// <param name="model">设备类型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] MachineryType model)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;
                var isSuccess = await Services.AddAsync(model);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败,请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-设备新增", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 修改设备
        /// </summary>
        /// <param name="model">修改设备</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] MachineryType model)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model);
                if (isSuccess)
                {
                    status.Msg = "修改成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败,请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-修改设备", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 批量删除设备
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] int[] Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Ids);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败,请稍后重试 。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-批量删除设备", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败,请稍后重试 。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-删除设备", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="设备类型编码",Fileld="MachineryTypeCode"},
                    new ReportDomain{ Title="设备类型名称",Fileld="MachineryTypeName"},
                    new ReportDomain{ Title="父类型",Fileld="ParentTypeId"},
                    new ReportDomain{ Title="是否启用",Fileld="EnableFlag"},
                    new ReportDomain{ Title="备注",Fileld="Remark"},
                    new ReportDomain{ Title="创建者",Fileld="Creator"},
                    new ReportDomain{ Title="创建时间",Fileld="CreateTime"},
                };
                var fileArray = BaseReport.Export(list, "设备类型信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "设备类型信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("设备类型-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }
    }
}
